<?php 
class ArrowCtrlCriteria extends ArrowTagContainer{
	
	public function configure(){
		$this->addProperties(array(
			"limit" => false,
			"groupBy" => false,
			"orderBy" => false
		));
		$this->setDisplay(false);
	}
	
	public function getCriteria(){
		$criterias = new Criteria();
		$models = $this->getChildren("ArrowCtrlModel");
		
		if(empty($models))
			throw new ArrowException("[ArrowCtrlCriteria] No model specified");
		if(count($models)==1){
			$criteria = new Criteria($models[0]->getModel());
		}else{
			$tmp = array();
			foreach($models as $model) $tmp[] = $model->getModel();
			$criteria = new ArrowOrmJoinCriteria($tmp);
		}
		
		$conditions = $this->getChildren("ArrowCtrlCondition");
		foreach($conditions as $condition){
			$criteria->addCondition( $condition->getField(), $condition->getValue(), $condition->getType() );
		}
		
		$limit = $this->getProperty("limit");
		if($limit != false){
			$tmp = explode(";", $limit);
			$criteria->setLimit($tmp[0], $tmp[1]);
		}
		
		$groupBy = $this->getProperty("groupBy");
		if($groupBy != false){
			$criteria->addGroupBy( $groupBy );
		}
	
		$orderBy = $this->getProperty("orderBy");
		if($orderBy != false){
			$fields = explode(';', $orderBy);
			
			foreach($fields as $field) {
				
				$tmp = explode(' ', $field);
				if(!isset($tmp[1]))
					$tmp[1] = 'asc';
				
				$criteria->addOrderBy( $tmp[0], $tmp[1] );
			}
		}
		
		$columns = $this->getChildren("ArrowCtrlColumn");
		if(!empty($columns)){
			$criteria->setEmptyList();
			foreach($columns as $column){
				$criteria->addColumn($column->getName());
			}
		}
		
		$virtualJoins = $this->getChildren("ArrowCtrlJoin");
		if(!empty($virtualJoins)){
			foreach($virtualJoins as $join){
				$criteria->addVirtualRelation($join->getProperty("baseClass"),$join->getProperty("baseField"),$join->getProperty("targetClass"),$join->getProperty("targetField"));
			}
		}	
		
		return $criteria;
	}
	
	public function setCriteria( $criteria ){
		return $this->setProperty("criteria", $criteria);
	}
}
?>